package com.jinbiao.quasar.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.jinbiao.quasar.constant.FileDir;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.UploadedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

@Component("fileService")
public class FileService {
    Logger logger = LoggerFactory.getLogger(FileService.class);
    @Inject(value = "${solon.staticfiles.mappings[0].path}", autoRefreshed = true)
    String path;
    @Inject(value = "${solon.staticfiles.mappings[0].repository}", autoRefreshed = true)
    String repository;
    @Inject(value = "${solon.staticfiles.mappings[0].host}", autoRefreshed = true)
    String host;

    public String saveFile(UploadedFile file) {
        String fileExt = file.getExtension();
        String fileName = IdUtil.getSnowflakeNextIdStr();
        try {
            file.transferTo(new File(StrUtil.format("{}{}.{}", repository, fileName, fileExt)));
            return StrUtil.format("{}{}{}.{}", host, path, fileName, fileExt);
        } catch (IOException e) {
            logger.error("上传文件错误:", e);
            return null;
        }
    }

    public String saveFile(UploadedFile file, String typeDir) {
        String fileExt = file.getExtension();
        String fileName = IdUtil.getSnowflakeNextIdStr();
        try {
            String parentDir = StrUtil.equals(typeDir, FileDir.DATE) ? "/" + DateUtil.format(DateUtil.date(), "yyyyMMdd") + "/" : typeDir;
            File targetFile = new File(StrUtil.format("{}{}{}.{}", repository, parentDir, fileName, fileExt));
            FileUtil.mkParentDirs(targetFile);
            file.transferTo(targetFile);
            return StrUtil.format("{}{}{}{}.{}", host, path, parentDir,fileName, fileExt);
        } catch (IOException e) {
            logger.error("上传文件错误:", e);
            return null;
        }
    }
}
